const _global = (typeof window !== 'undefined' ? window : global || {});

export default class Storage {

  constructor(options = {}) {
    this._options = {
      ...options,
      storage: options.storage || 'local',
      name: options.name || 'ls',
      namespace: ''
    }
    this.store = null;
    this.install(this._options);

    // length
    Object.defineProperty(this, 'length', {
      get() {
        return this.store.length;
      },
    });
  }

  install(options = {}) {
    // 只支持 'local', 'session' storage
    if (options.storage && ['local', 'session'].indexOf(options.storage) === -1) {
      throw new Error(`Storage "${options.storage}" is not supported`);
    }

    switch(options.storage) { 
      case 'local':
        this.store = 'localStorage' in _global
          ? _global.localStorage
          : null
        ;
        break;

      case 'session':
        this.store = 'sessionStorage' in _global
          ? _global.sessionStorage
          : null
        ;
        break;
    }
  }
  // 设置属性
  set(name, value, expire = null) {
    const stringifyValue = JSON.stringify({
      value,
      expire: expire !== null ? new Date().getTime() + expire : null,
    });
    this.store.setItem(this._options.namespace + name, stringifyValue);
  }
  // 获取属性
  get(name, def = null) {
    const item = this.store.getItem(this._options.namespace + name);
    if (item !== null) {
      try {
        const data = JSON.parse(item);

        if (data.expire === null) {
          return data.value;
        }

        if (data.expire >= new Date().getTime()) {
          return data.value;
        }

        // this.remove(name);
      } catch (err) {
        return def;
      }
    }

    return def;
  }
  key(index) {
    return this.store.key(index);
  }
  remove(name) {
    return this.store.removeItem(this._options.namespace + name);
  }
};